namespace TeamMatches
{
    using Helper;
    using System;
    using System.Diagnostics;
    using System.IO;
    using System.Threading;

    public class TeamMatches
    {
        #region Member Fields
        private HttpHelper _hh = new HttpHelper();
        private const string c_ConfigFile = "Config.txt";
        private const string c_MasterIDsFile = "MasterIDs.txt";
        private const string c_SlaveIDsFile = "SlaveIDs.txt";
        private int _MidnightForce = -1;
        private string _MatchMidnight = "24:00";
        //private string _Path = Path.GetDirectoryName(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
        private string _Path = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName);
        #endregion

        // 登录账号
        private bool Logon(string username, string password)
        {
            return (this.LogonAndGetId(username, password) > 0);
        }

        // 登录账号 并获取用户 ID
        private int LogonAndGetId(string username, string password)
        {
            TraceLog.Print("Login as [{0}]: ", username);
            string content = _hh.Post("http://www.kaixin001.com/login/login.php", "url=%2F&email=" + HttpHelper.EncodePostData(username) + "&password=" + HttpHelper.EncodePostData(password));

            if (content.IndexOf("<title>我的首页 - 开心网</title>") != -1)
            {
                int pos;
                string strId = ContentHelper.GetMidString(content, "我的开心网ID:", "\"", out pos);
                int id = -1;
                if (strId != null)
                {
                    try
                    {
                        id = Int32.Parse(strId);
                    }
                    catch (OverflowException)
                    {
                    }
                    catch (FormatException)
                    {
                    }
                }
                TraceLog.PrintLn("Ok!, Id={0}", id);
                return id;
            }
            else
            {
                TraceLog.Error("Failed!");
                return -1;
            }
        }


        private void MatchDetail()
        {
            int pos;
            string content = _hh.Get("http://www.kaixin001.com/app/app.php?aid=1040&url=myteam.php");

            string myMatchUid = ContentHelper.GetMidString(content, "<a href=\"javascript:matchDetail(", ",", out pos);
            if (null != myMatchUid)
                content = content.Substring(pos);

            string matchUid = ContentHelper.GetMidString(content, "<a class=\"sl\" href=\"javascript:matchDetail(", " ,", out pos);
            if (null == matchUid)
            {
                return;
            }
            content = content.Substring(pos);
            string matchId = ContentHelper.GetMidString(content, " , ", ")", out pos);
            while (null != matchUid && null != matchId)
            {
                content = content.Substring(pos);

                if (myMatchUid != matchUid) // 跳过自己参与的比赛
                    TeamOil(matchUid, matchId);

                matchUid = ContentHelper.GetMidString(content, "javascript:matchDetail(", " ,", out pos);
                if (null == matchUid)
                {
                    break;
                }
                content = content.Substring(pos);
                matchId = ContentHelper.GetMidString(content, " , ", ")", out pos);
            }
        }

        private void ReadGlobalConfig()
        {
            try
            {
                string path = _Path + Path.DirectorySeparatorChar + c_ConfigFile;
                if (!File.Exists(path))
                {
                    TraceLog.PrintLn("缺少{0}文件，系统加载默认配置.", new object[] { path });
                }
                else
                {
                    GlobalConfigData globalConfigData = GlobalConfigHelper.ReadGlobalConfigData(path);
                    this._hh.SetConfig(globalConfigData);
                    _MidnightForce = globalConfigData.MidnightForce;
                    _MatchMidnight = globalConfigData.MatchMidnight;
                    TraceLog.WriteToFile = globalConfigData.WriteToLogFile;
                }
            }
            catch (Exception exception)
            {
                TraceLog.Error(exception.Message);
            }
        }

        public void Run()
        {
            this.ReadGlobalConfig();

            if (!File.Exists(_Path + Path.DirectorySeparatorChar + c_MasterIDsFile))
            {
                TraceLog.Error("{0}文件不存在！", c_MasterIDsFile );
                return;
            }
            if (!File.Exists(_Path + Path.DirectorySeparatorChar + c_SlaveIDsFile))
            {
                TraceLog.Error("{0}文件不存在！", c_SlaveIDsFile );
                return;
            }
            if (_MidnightForce >= 0)
            {
                while (true)
                {
                    DateTime dt = System.DateTime.Now.ToLocalTime();
                    DateTime bdt = dt.AddMinutes(-_MidnightForce);
                    DateTime edt = dt.AddMinutes(_MidnightForce);
                    string cTime = _MatchMidnight;
                    string bTime = string.Format("{0:D2}:{1:D2}", bdt.Hour == 0 ? 24 : bdt.Hour, bdt.Minute);
                    string eTime = string.Format("{0:D2}:{1:D2}", edt.Hour == 0 ? 24 : edt.Hour, edt.Minute);
                    if ((string.Compare(bTime, cTime) <= 0) && (string.Compare(cTime, eTime) <= 0))
                    {
                        TraceLog.PrintLn("CurTime:{0} force run...", dt);
                        RunTeamMatches();
                    }
                    TraceLog.PrintLn("Wait 1 mins to restart...");
                    Thread.Sleep(60 * 1000);
                }
            }
            else
            {
                DateTime dt = System.DateTime.Now.ToLocalTime();
                TraceLog.PrintLn("CurTime:{0} force run...", dt);
                RunTeamMatches();
                TraceLog.PrintLn("按任意键退出....");
                Console.ReadKey();
            }
        }

        private void RunTeamMatches()
        {
            // 读取所有Id
            string[] masterLines = File.ReadAllLines(_Path + Path.DirectorySeparatorChar + c_MasterIDsFile);
            string[] slaveLines = File.ReadAllLines(_Path + Path.DirectorySeparatorChar + c_SlaveIDsFile);
            TraceLog.PrintLn("");

            TraceLog.PrintLn("开始为好友加油：");
            for (int i = 0; (i + 1) < slaveLines.Length; i += 2)
            {
                this.Logon(slaveLines[i], slaveLines[i + 1]); // 逐个登录从号
                this.MatchDetail();
            }
            for (int j = 0; (j + 1) < masterLines.Length; j += 2)
            {
                this.Logon(masterLines[j], masterLines[j + 1]); // 逐个登录主号
                this.MatchDetail();
                this.TeamBegin();
            }
            TraceLog.PrintLn("");
        }

        private void TeamBegin()
        {
            try
            {
                int pos;
                string content = _hh.Get("http://www.kaixin001.com/app/app.php?aid=1040&url=myteam.php");
                string myMatchUid = ContentHelper.GetMidString(content, "<a href=\"javascript:matchDetail(", ",", out pos);
                if (null == myMatchUid) // 没有车队
                {
                    TraceLog.PrintLn("对不起，您还没有自己的车队");
                    return;
                }
                content = content.Substring(pos);
                string myMatchId = ContentHelper.GetMidString(content, ",", ")", out pos);

                int pos1;
                content = _hh.Get("http://www.kaixin001.com/app/app.php?aid=1040&url=match.php&matchuid=" + myMatchUid + "&matchid=" + myMatchId);
                // 今天比赛已经启动
                if (content.IndexOf("你的车队今天已经启动") != -1)
                {
                    TraceLog.PrintLn("你的车队今天已经启动");
                    return;
                }

                // 开始启动比赛
                string verifyCode = ContentHelper.GetVerifyCode(content);
                string teamuid = ContentHelper.GetMidString(content, "javascript:teamBegin(", ",", out pos1);
                content = content.Substring(pos1);
                string teamid = ContentHelper.GetMidString(content, ",", ")", out pos1);
                _hh.Get("http://www.kaixin001.com/parking/teambegin.php?verify=" + verifyCode + "&teamuid=" + teamuid + "&teamid=" + teamid);
                TraceLog.PrintLn("成功启动比赛");
            }
            catch (Exception)
            {
                //TraceLog.Error("不能启动比赛！原因是：{0}", new string[] { ex.Message });
                TraceLog.Error("不能启动比赛！可能赛车已经启动过了。");
            }
        }

        private void TeamOil(string matchuid, string matchid)
        {
            try
            {
                int pos;
                string content = _hh.Get("http://www.kaixin001.com/app/app.php?aid=1040&url=match.php&matchuid=" + matchuid + "&matchid=" + matchid);
                string verifyCode = ContentHelper.GetVerifyCode(content);

                // 左边部分加油
                string teamuid = ContentHelper.GetMidString(content, "javascript:oil(", ",", out pos);
                content = content.Substring(pos);
                string teamid = ContentHelper.GetMidString(content, ",", " , 1)", out pos);
                String oliResult = _hh.Get("http://www.kaixin001.com/parking/teamoil.php?verify=" + verifyCode + "&teamuid=" + teamuid + "&teamid=" + teamid + "&type=1");
                ShowOilResult(oliResult);

                // 跳过左边部分捣鬼
                content = content.Substring(pos);
                ContentHelper.GetMidString(content, "javascript:oil(", ")", out pos);

                // 右边部分加油
                content = content.Substring(pos);
                teamuid = ContentHelper.GetMidString(content, "javascript:oil(", ",", out pos);
                content = content.Substring(pos);
                teamid = ContentHelper.GetMidString(content, ",", " , 1)", out pos);
                oliResult = _hh.Get("http://www.kaixin001.com/parking/teamoil.php?verify=" + verifyCode + "&teamuid=" + teamuid + "&teamid=" + teamid + "&type=1");
                if (ShowOilResult(oliResult))
                    TraceLog.PrintLn("加油成功！");
                else
                    TraceLog.PrintLn("不能为好友加油，可能已经加满油！");
            }
            catch (Exception ex)
            {
                TraceLog.Error("不能为好友加油！原因是：{0}", new string[] { ex.Message });
            }
        }

        private bool ShowOilResult(string content)
        {
            content = ContentHelper.GetMidString(content, "display:block", "</strong>");
            if (String.IsNullOrEmpty(content))
                return false;
            TraceLog.PrintLn(ContentHelper.NoHtml(content));
            return true;
        }
    }
}

